<template>
  <div>
    <div class="gva-table-box">
      <el-table
        ref="multipleTable"
        :data="tableData"
        style="width: 100%"
        @row-click="handleRowClick"
        tooltip-effect="dark"
        row-key="ID"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="left" label="标题" prop="title" width="150" />
        <el-table-column align="left" label="需求" prop="require" width="200" />

        <el-table-column
          align="left"
          label="需求方"
          prop="publisher"
          width="150"
        />
        <el-table-column
          align="left"
          label="技术方"
          prop="candidates"
          width="200"
        />

        <el-table-column align="left" label="价格" width="150">
          <template #default="scope">
            <div>{{ scope.row.ex_price }} 元</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="是否支付" width="150">
          <template #default="scope">
            <div>{{ scope.row.is_paid == true ? "已支付" : "未支付" }}</div>
          </template>
        </el-table-column>
        <el-table-column align="left" label="匹配成功时间" width="150">
          <template #default="scope">
            <div>{{ new Date(scope.row.updated_at).toLocaleString() }}</div>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="其他要求"
          prop="other"
          width="180"
        />

        <!-- 操作列 -->
        <el-table-column align="right" label="操作" min-width="200">
          <template #default="scope">
            <el-button
              type="primary"
              link
              icon="edit"
              @click.stop="updateCustomer(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <div class="gva-pagination">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>

    <!-- 编辑抽屉部分 -->
    <el-drawer
      v-model="drawerFormVisible"
      :before-close="closeDrawer"
      :show-close="false"
      size="30%"
      direction="rtl"
    >
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg font-bold">订单处理选项</span>
          <el-button icon="close" @click="closeDrawer" circle></el-button>
        </div>
      </template>

      <el-form :inline="false" :model="form" label-width="120px">
        <el-form-item label="订单状态">
          <el-select v-model="form.orderStatus" placeholder="请选择订单状态">
            <el-option label="订单完成" value="0"></el-option>
            <el-option
              label="订单失败(技术方没有做出来)"
              value="failed"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.orderStatus === 'failed'" label="失败处理方式">
          <el-select v-model="form.failureOption" placeholder="请选择处理方式">
            <el-option label="重新发布业务大厅" value="1"></el-option>
            <el-option label="更改成内部技术人员" value="2"></el-option>
            <el-option label="删除订单" value="3"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="form.failureOption === '2'" label="输入手机号">
          <el-input v-model="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
      </el-form>

      <div class="flex justify-end mt-4">
        <el-button @click="closeDrawer" size="small">取 消</el-button>
        <el-button type="primary" @click="enterDrawer('submit')" size="small">
          提 交
        </el-button>
      </div>
    </el-drawer>

    <el-dialog
      v-model="dialogFormVisible"
      width="50%"
      :before-close="closeDialog"
    >
      <template #title>
        <div>订单详情</div>
      </template>

      <OrderDetail v-if="dialogFormVisible" :orderId="currentOrderId" />

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getMatchedOrderList, updateFinishOrder } from "@/api/order";
import OrderDetail from "@/components/OrderDetails.vue";

const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const tableData = ref([]);
const dialogFormVisible = ref(false);
const currentOrderId = ref(0);
// 处理点击行跳转
const handleRowClick = (row) => {
  currentOrderId.value = row.order_id;
  dialogFormVisible.value = true; // 跳转到 OrderDetails 页面，并传递 id
};

const closeDialog = () => {
  dialogFormVisible.value = false;
};
// 获取表格数据的函数
const getTableData = async () => {
  tableData.value = [];
  const table = await getMatchedOrderList({
    page: page.value,
    pageSize: pageSize.value,
    type: 1,
  });
  if (table.code === 0) {
    table.data.list.forEach((item) => {
      item.candidateDeatils = item.candidates;
      let candidates = [];
      if (!item.candidates || item.candidates.length === 0) {
        item.candidates = "暂无候选人";
      } else {
        item.candidates.forEach((c) => {
          candidates.push(c.nickname);
        });
        item.candidates = candidates.join(",");
      }
    });
    tableData.value = table.data.list;
    total.value = table.data.total;
    page.value = table.data.page;
    pageSize.value = table.data.pageSize;
  }
};

getTableData();

// 控制编辑抽屉显示/隐藏的逻辑
const drawerFormVisible = ref(false);
const form = ref({
  orderStatus: "",
  failureOption: "",
  row: {},
  phone: "", // 重置手机号
});

const updateCustomer = async (row) => {
  drawerFormVisible.value = true;
  form.value.row = row;
};

const closeDrawer = () => {
  drawerFormVisible.value = false;
  form.value = {
    orderStatus: "",
    failureOption: "",
    row: {},
    phone: "", // 重置手机号
  };
};

const enterDrawer = async (action) => {
  if (action === "submit") {
    if (form.value.orderStatus === "0") {
      const res = await updateFinishOrder({
        type: 0,
        orderId: form.value.row.order_id,
      });
      ElMessage.success("订单已完成");
    } else if (form.value.orderStatus === "failed") {
      if (!form.value.failureOption) {
        ElMessage.warning("请选择订单失败后的处理方式");
        return;
      }
      if (form.value.failureOption === "1") {
        const res = await updateFinishOrder({
          type: 1,
          orderId: form.value.row.order_id,
        });
        ElMessage.info("订单已重新发布到业务大厅");
      } else if (form.value.failureOption === "2") {
        if (!form.value.phone) {
          ElMessage.warning("请填写手机号");
          return;
        }
        const res = await updateFinishOrder({
          type: 2,
          orderId: form.value.row.order_id,
          phone: form.value.phone,
        });
        ElMessage.info("订单已分配给内部技术人员");
      } else if (form.value.failureOption === "3") {
        ElMessageBox.confirm("确定要删除此订单吗?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await updateFinishOrder({
              type: 3,
              orderId: form.value.row.order_id,
            });
            ElMessage.success("订单已删除");
          })
          .catch(() => {
            ElMessage.info("已取消删除");
          });
      }
    }
    getTableData();
    closeDrawer();
  }
};
</script>

<style scoped>
.gva-btn-list {
  margin-bottom: 20px;
}
.el-button {
  margin-left: 10px;
}
.flex {
  display: flex;
  justify-content: space-between;
}
.mt-4 {
  margin-top: 16px;
}
</style>
